﻿using eslib.nnp5.Matchers;
using System;
using System.Linq;

namespace eslib.nnp5.layers
{
    /// <summary>
    /// 微型FF协议传输层支持
    /// </summary>
    public class MicroFFTransportLayer : ITransportLayer
    {
        /// <summary>
        /// 连接器
        /// </summary>
        public Connector connector { get; private set; }

        private MicroFFMatcher matcher;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="connector"></param>
        public MicroFFTransportLayer(Connector connector)
        {
            this.connector = connector;

            matcher = new MicroFFMatcher();
            matcher.matchEvent += Matcher_matchEvent;

            connector.RecvEvent += Connector_RecvEvent;
        }



        private void Connector_RecvEvent(Connector connector, byte[] buffer, int len)
        {
            matcher.inStream(buffer.Take(len).ToArray());     //必需只取len
        }




        /// <summary>
        /// 重置
        /// </summary>
        public void Reset()
        {
            matcher.reset();
        }


        /// <summary>
        /// 发送数据,data为原始数据
        /// </summary>
        /// <param name="data">原始数据</param>
        public void sendData(byte[] data)
        {
            //转换为MicroFF数据协议格式,并发送
            connector.send(MicroFFMatcher.transInData(data));       //transInData已包含包头包尾
        }



        #region 解包部分

        private void Matcher_matchEvent(byte[] buf)
        {
            //MicroFFMatcher已自带解包功能
            //引发事件
            NewTransportLayerDataEvent?.Invoke(buf);
        }

        #endregion


        /// <summary>
        /// 新MicroFF协议数据包事件
        /// </summary>
        public event NewTransportLayerDataEventHandler NewTransportLayerDataEvent;

    }

}